package com.zzyl.controller.customer;

import com.zzyl.base.ResponseResult;
import com.zzyl.constant.Constants;
import com.zzyl.controller.BaseController;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import com.zzyl.properties.JwtTokenManagerProperties;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/customer/user")
public class CustomerUserController extends BaseController {

    @Autowired
    private WeChatService weChatService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @PostMapping("/login")
    @ApiOperation("登录")
    public ResponseResult<LoginVo> login(@RequestBody UserLoginRequestDto userLoginRequestDto){

        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());
        System.out.println(openId);
        String weChatServiceAccessToken = weChatService.getAccessToken();
        System.out.println(weChatServiceAccessToken);
        String phoneNumber = weChatService.getPhoneNumber(weChatServiceAccessToken,userLoginRequestDto.getPhoneCode(),openId);
        System.out.println(phoneNumber);
        //1.appid和secret和code获取openid
        //获取phoneNumber
        //2.通过openid获取用户信息,判断用户是否存在
        Member m = memberMapper.getMemberById(openId);
        if(m==null){
            Member member = new Member();
            member.setOpenId(openId);
            member.setPhone(phoneNumber);
            member.setGender(0);
            member.setName("Rex");
            memberMapper.insertMember(member);
            m = memberMapper.getMemberById(openId);
        }else {
            String phone = m.getPhone();
            if(!phoneNumber.equals(phone)){
                m.setPhone(phoneNumber);
                memberMapper.updateMember(m);
            }
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, m.getId());
        claims.put(Constants.JWT_USERNAME, m.getName());

        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
        //2.1不存在创建用户
        //2.2存在
        //2.3获取PhoneCode,查询手机号
        //2.4判断手机号是否一致，不一一致，更新手机号
        //3获取用户id，jwt生产token,返回
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(m.getName());
        return success(loginVo);

    }
}
